﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using frag_boardgame;

namespace GameService
{
    public class UserInfo
    {

        public struct Message
        {
            public string Text;
            public string Sender;
            public bool UpdateGameData;
            public bool IsGameOver;
            public bool ToggleCurrentPlayer;
        }

        public PlayerConfiguration config;
        public long? Uid;
        private List<Message> messages = new List<Message>();
        private int messagesRead = 0;        

        private void AddMessage(Message message) 
        {
            lock(messages)
            {
                messages.Add(message);
            }
        }

        public void AddMessage(string sender, string text)
        {
            AddMessage(new Message() { Text = text, Sender = sender });
        }

        public void Update(string message)
        {
            AddMessage(new Message() { Text = message, UpdateGameData = true });
        }

        public void GameOver(string message)
        {
            AddMessage(new Message() { Text = message, IsGameOver = true });
        }

        public void ToggleCurrentPlayer()
        {
            AddMessage(new Message() { ToggleCurrentPlayer = true });
        }

        /// <summary>
        /// Get the latest messages
        /// </summary>
        /// <param name="onlyNew">Return only new messages since the last query</param>
        /// <returns></returns>
        public List<Message> GetMessages(bool onlyNew)
        {
            // Return a copy of the messages, so we can continue working
            lock (messages)
            {
                List<Message> ret;
                int tmp = messages.Count;
                if (!onlyNew)
                {
                    ret = messages.ToList();
                }
                else
                {
                    ret = messages.GetRange(messagesRead, messages.Count - messagesRead);
                }
                messagesRead = tmp;
                return ret;
            }
        }

        public void ClearMessages()
        {
            lock (messages)
            {
                messages.Clear();
                messagesRead = 0;
            }
        }

    }
}
